package com.jmga.ecogasfinder.services;

import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;

import com.google.android.maps.MapView;
import com.jmga.ecogasfinder.providers.GasFinderProvider;
import com.jmga.ecogasfinder.utilities.Tools;

public class EcoStationProducerService extends Service {
	MapView myMapView = null;
	public static final String SHOW_TOP_TEN = "SHOW_TOP_TEN";
	
	@Override
	public void onCreate() {
		super.onCreate();
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.d(getClass().getName(), "onStartCommand: " + intent.getAction() + "Flags: " + flags + " startId " + startId);
		if ((flags & START_FLAG_RETRY) == 0) {
			// if it's a restart, do something.
		} else {
			// Alternative background process.
		}

		ecoStationSearcher();

		return START_STICKY;
	}
	
	private void ecoStationSearcher() {
		ECOGasStationUpdaterTask gasStationUpdater = new ECOGasStationUpdaterTask();
		Object[] parameters = new Object[0];
		
		gasStationUpdater.execute(parameters);
	}
	
	private class ECOGasStationUpdaterTask extends AsyncTask<Object, Void, Void> {
		@Override
		protected Void doInBackground(Object... params) {
			Cursor frequencyCursor;
			ContentValues values = new ContentValues();
			String whereObservable = GasFinderProvider.KEY_OBSERVABLE + " = 1";
			String timesOrderDesc = GasFinderProvider.KEY_TIMES + " DESC";
			
			values.put(GasFinderProvider.KEY_OBSERVABLE, Integer.valueOf(0));
			
			int updated = getContentResolver().update(GasFinderProvider.CONTENT_URI_STATIONS, values, whereObservable, null);
			Log.d(getClass().getName(), "stations updated to Observable = 0 --> " + updated);
			
			int[] frequencies = null;
			frequencyCursor = getContentResolver().query(GasFinderProvider.CONTENT_URI_FREQUENCY, null, null, null, timesOrderDesc);

			if(frequencyCursor.getCount() != 0) {
				frequencies = new int[frequencyCursor.getCount()];
				
				for(int i=0; i < frequencyCursor.getCount();i++) {
					frequencyCursor.moveToNext();
					frequencies[i] = frequencyCursor.getInt(frequencyCursor.getColumnIndex(GasFinderProvider.KEY_TIMES));
				}
			}			
			frequencyCursor.close();
			
			if(frequencies != null && frequencies.length > 0) {
				double standardDeviation = Tools.getStandardDeviation(frequencies);
				Log.d(getClass().getName(), "Frequency - Mean " + Tools.getMean(frequencies) + " StdDevt " + standardDeviation);
				
				String timesWhere = GasFinderProvider.KEY_TIMES + " >= " + standardDeviation;
				String stations = "";
				
				frequencyCursor = getContentResolver().query(GasFinderProvider.CONTENT_URI_FREQUENCY, null, timesWhere, null, null);
				
				if(frequencyCursor.getCount() != 0) {
					while(frequencyCursor.moveToNext()) {
						stations += "'" + frequencyCursor.getString(frequencyCursor.getColumnIndex(GasFinderProvider.KEY_STATION)) + "',";
					}
				}		
				
				String stationWhere = null;
				String[] stationArgs = new String[1];
				
				if(!stations.isEmpty()){
					stationArgs[0] = stations.substring(0, stations.length() - 1);
					stationWhere = GasFinderProvider.KEY_X_COORD + " || " + GasFinderProvider.KEY_Y_COORD + " IN (" + stationArgs[0] + ")";
				}
				
				values = new ContentValues();
				values.put(GasFinderProvider.KEY_OBSERVABLE, Integer.valueOf(1));				
				
				updated = getContentResolver().update(GasFinderProvider.CONTENT_URI_STATIONS, values, stationWhere, null);
				Log.d(getClass().getName(), "stations updated to Observable = 1 --> " + updated);
			}
				
			return null;
	    }
		
		@Override
	    protected void onProgressUpdate(Void... values) {

	    }
	
	    @Override
	    protected void onPostExecute(Void result) {
	    	stopSelf();
	    }
	}
	
}
